<template>
    <el-popover
      v-model="isShow"
      width="416"
      ref="myPopover"
      @show="showPopover"
      :popper-class="popperClass"
      placement="bottom-start"
      transition="el-zoom-in-top"
      :visible-arrow="false"
      trigger="click">
      <el-input  slot="reference" :style="{width:width+'px'}" :placeholder="placeholder"
      ref="input"
      readonly  
      style="cursor:pointer" v-model="text">
            <i slot="suffix" class="el-select__caret el-input__icon el-icon-arrow-up" 
            :class="{ 'is-reverse' : isShow}"></i>
      </el-input>
      <div class="content" :style="{'max-height':maxHeight+'px', 'overflow-y':'auto'}">
        <el-checkbox v-model="checkedAll" @change="checkedAllHandler" v-if="data.length>1">全选</el-checkbox>
        <ul v-if="data.length">
            <li v-for="(item,index) in data" :key="index">
                <div class="top" @click="zoom(item)">
                  <el-checkbox v-model="item.checked" v-if="showCheckbox"  @change="checked=>checkRow(checked, item)">{{ item.label }}</el-checkbox>
                  <span v-else >{{ item.label }}</span>
                  <i class="el-select__caret el-icon-arrow-up"  :class="{ 'is-reverse' : item.childshow}" ></i>
                </div>
                <el-collapse-transition>  
                  <ul class="child"  v-show="item.childshow"> 
                      <li v-for="(v,i) in item.children" :key="i">
                        <el-checkbox v-if="showCheckbox" v-model="v.checked" @change="checked=>change(checked, v,item)">{{v.label}}</el-checkbox>
                        <el-radio v-else v-model="radioModel" :label="v.id" @change="checked=>changeRadio(checked, v,item)">{{v.label}}</el-radio>
                      </li>
                  </ul>
                </el-collapse-transition>   
            </li>
        </ul>
        <div v-else style="text-align:center;">暂无数据</div>
      </div>
    </el-popover>
</template>
<script>
export default {
  props: {
    placeholder: String,
    width: {
      type: Number,
      default: 200
    },
    showCheckbox: {
      type: Boolean,
      default: true
    },
    accordion: { // 是否每次只展开一层
      type: Boolean,
      default: false
    },
    dataGrid: Array,
    checkedKeys: Array // 默认选中

  },
  data() {
    return {
      checkedAll: false,
      isShow: false,
      radioModel: 'radio',
      checkedNodes: [],
      first: null,
      value: '',
      maxHeight: 200,
      show: true,
      data: this.handle(this.dataGrid),
      checkedList: []// 选中的checkbox

    };
  },
  computed: {
    text() {
      const checkedList = this.checkedList;
      const len = checkedList.length;
      const placeholder = this.placeholder;
      if (len === 0) {
        return placeholder;
      } else if (len === 1) {
        return checkedList[0].label;
      } else {
        return `${placeholder}(${len})`;
      }
    },
    layoutSkin: {
      get() { return this.$store.state.common.layoutSkin; }
    },
    popperClass() {
      if (this.layoutSkin === 'dark') {
        return 'pollute-group-popover pollute-group-popover--dark';
      } else {
        return 'pollute-group-popover';
      }
    }
  },
  methods: {
    checkedAllHandler(checked) {
      this.data.forEach(v => {
        const child = v.children;
        child.forEach(ele => {
          ele.checked = checked;
        });
      });
      this.getCheckedList(this.data);
    },
    checkRow(checked, item) {
      console.log(checked, item);
      const id = item.id;
      this.data.forEach(v => {
        if (v.id === id) {
          const child = v.children;
          child.forEach(ele => {
            ele.checked = checked;
          });
        }
      });
      // console.log('data', this.data);
      this.getCheckedList(this.data);
    },
    change(checked, v, item) {
      this.getCheckedList(this.data);
    },
    changeRadio(v) {
      var ary = [];
      var each = data => {
        data.forEach(item => {
          if (item.children.length) {
            each(item.children);
          } else {
            ary.push(item);
          }
        });
      };
      each(this.data);
      this.radioModel = v;
      this.checkedList = ary.filter(item => item.id === v);
    },
    deepClone(obj) {
      let tmp = '';
      let result = '';
      tmp = JSON.stringify(obj);
      result = JSON.parse(tmp);
      return result;
    },
    handle(dataGrid) {
      var arr = this.deepClone(dataGrid);
      arr.forEach(item => {
        item.childshow = false;
        item.checked = false;
        item.id = item.id + '';
        if (item.children) {
          item.children.forEach(v => {
            v.checked = false;
            v.parentID = item.id;
            if (this.first === null && !this.showCheckbox) {
              this.first = v;
              item.childshow = true;
            }
          });
        }
      });
      return arr;
    },

    zoom(item) {
      if (item.children.length) {
        const id = item.id;
        this.data.forEach(v => {
          if (v.id === id) {
            v.childshow = !v.childshow;
          } else {
            this.accordion && (v.childshow = false);
          }
        });
      }
    },
    // 获取选中的checkbox
    getCheckedList(array) {
      var ary = [];
      var each = data => {
        data.forEach(item => {
          if (item.children.length) {
            each(item.children);
          } else {
            ary.push(item);
          }
        });
      };
      each(array);
      this.checkedList = ary.filter(item => item.checked === true);
    },
    // 自动选中
    autoCheck() {
      if (this.showCheckbox) {
        if (this.checkedKeys && this.checkedKeys.length) {
          const id = this.checkedKeys;
          let flag = false;
          const each = data => {
            data.forEach(item => {
              item.checked = false;
              if (id.indexOf(item.id) > -1) {
                item.checked = true;
                flag = true;
              }
              if (item.children) {
                each(item.children);
              }
            });
          };
          each(this.data);
          if (flag) {
            this.getCheckedList(this.data);
          }
        } else {
          this.checkedList = [];
        }
      } else {
        if (this.first !== null) {
          this.changeRadio(this.first.id);
        }
      }
    },
    // 动态设置最大高度
    showPopover() {
      const self = this;
      self.clientHeight = document.documentElement.clientHeight;
      self.maxHeight = self.clientHeight * 0.6;
      self.$refs.myPopover.popperElm.style.maxHeight = self.maxHeight + 'px';
    }
  },

  watch: {
    dataGrid(n, o) {
      this.data = this.handle(n);
    },
    data(n, o) {
      this.autoCheck();
    },
    checkedKeys(n, o) {
      this.autoCheck();
    },
    checkedList(n, o) {
      this.data.forEach(item => {
        const check = item.children.map(v => v.checked).filter(v => v === true);
        if (item.children.length > 0 && (item.children.length === check.length)) {
          item.checked = true;
        } else {
          item.checked = false;
        }
        item.children.forEach(v => {
          if (v.checked === true) {
            item.childshow = true;
          }
        });
      });
      this.checkedAll = this.data.filter(v => v.checked === true).length === this.data.length;
      this.$emit('change', n);
    }

  }
};
</script>

<style lang="scss" scoped="">
@import '~@/assets/scss/variables';
  .el-select__caret {
    color: #c0c4cc;
    font-size: 14px;
    transition: transform .3s;
    transform: rotate(180deg);
    cursor: pointer;
  }
  .el-select__caret.is-reverse {
    transform: rotate(0deg);
  }
  .pollute-group-popover{
      .content{
          .top{
            cursor: pointer;padding-right: 5px;
            height: 26px;line-height: 26px;
            i{
              margin: 6px 0; float: right;
            }
          }
          .top:hover{background-color: #f5f7fa;}
          ul li {list-style-type:none;  overflow: hidden;}
          .child{
              overflow: hidden;margin-top:5px;
              // transition: height 0.2s;
              li{
                float: left;
                border-radius: 3px;
                margin-right: 10px;
                margin-bottom: 5px;
                background: #e1e5ed;
                padding: 5px 7px;
              }
              li:hover{
                background-color: #c8daf1;
              }
          }
      }

      &--dark{
        .content{
          .top:hover{background-color: $item-hover-color-dark;} 
          .child{
            li{
            background: #315aac;
            }
            li:hover{
              background-color: $item-hover-color-dark;
            }
          }
        }
      }
  }
</style>
